<template>
    <div class="form">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
            <h2>业主方联系方式</h2>
            <a-form-model-item label="单位" prop="unit">
                <a-input
                    v-model="form.unit"
                    :maxLength="100"
                    placeholder="请输入单位"
                    v-if="!isDetail"
                    :disabled="isDetail"
                ></a-input>
                <p class="form-detail-text" v-else>{{ form.unit }}</p>
            </a-form-model-item>
            <a-form-model-item label="联系人" prop="contacts">
                <a-input
                    v-model="form.contacts"
                    :maxLength="20"
                    placeholder="请输入联系人"
                    :disabled="isDetail"
                ></a-input>
            </a-form-model-item>
            <a-form-model-item label="联系方式" prop="contactsPhoneNumber">
                <a-input
                    v-model="form.contactsPhoneNumber"
                    :maxLength="11"
                    placeholder="请输入联系方式"
                    :disabled="isDetail"
                ></a-input>
            </a-form-model-item>
            <h2>招商策划书（含投资估算及效益分析）</h2>
            <a-tabs v-model="form.actualCapitalType" v-if="!isDetail">
                <a-tab-pane :key="1" tab="文件上传"></a-tab-pane>
                <a-tab-pane :key="2" tab="富文本"></a-tab-pane>
            </a-tabs>
            <template v-if="form.actualCapitalType === 1">
                <custom-upload-dragger
                    v-if="!isDetail"
                    v-model="form.actualCapitalPlan"
                    :typeList="['application/pdf']"
                    :max="6"
                    :fileSize="10"
                    path="need-manage/doc"
                    tipText="只能上传PDF文件，且不超过10M，最大上传数量6个"
                ></custom-upload-dragger>
                <div class="file-box" v-else>
                    <template v-for="(item, index) in form.actualCapitalPlan">
                        <a-button type="link" :key="index" @click="toOpen(item)">
                            {{ item.split('?name=')[1] }}
                        </a-button>
                    </template>
                </div>
            </template>
            <template v-if="form.actualCapitalType === 2">
                <a-form-model-item label="文件标题" prop="actualCapitalTitle">
                    <a-input v-model="form.actualCapitalTitle" :maxLength="20" :disabled="isDetail"></a-input>
                </a-form-model-item>
                <a-form-model-item label="富文本详情" prop="actualCapitalDescription">
                    <tinymce-editor
                        v-model="form.actualCapitalDescription"
                        cosPath="need-manage/img"
                        :height="400"
                        :disabled="isDetail"
                    ></tinymce-editor>
                </a-form-model-item>
            </template>
            <h2>地方政府招商引资文件/投资机会文件下载<span>投资环境介绍或招商政策等</span></h2>
            <a-tabs v-model="form.governmentActualCapitalType" v-if="!isDetail">
                <a-tab-pane :key="1" tab="文件上传"></a-tab-pane>
                <a-tab-pane :key="2" tab="富文本"></a-tab-pane>
            </a-tabs>
            <template v-if="form.governmentActualCapitalType === 1">
                <custom-upload-dragger
                    v-if="!isDetail"
                    v-model="form.governmentActualCapital"
                    :typeList="['application/pdf']"
                    :max="6"
                    :fileSize="10"
                    path="need-manage/doc"
                    tipText="只能上传PDF文件，且不超过10M，最大上传数量6个"
                ></custom-upload-dragger>
                <div class="file-box" v-else>
                    <template v-for="(item, index) in form.governmentActualCapital">
                        <a-button type="link" :key="index" @click="toOpen(item)">
                            {{ item.split('?name=')[1] }}
                        </a-button>
                    </template>
                </div>
            </template>
            <template v-if="form.governmentActualCapitalType === 2">
                <a-form-model-item label="文件标题" prop="governmentActualCapitalTitle">
                    <a-input
                        v-model="form.governmentActualCapitalTitle"
                        placeholder="请输入文件标题"
                        :maxLength="20"
                        :disabled="isDetail"
                    ></a-input>
                </a-form-model-item>
                <a-form-model-item label="富文本详情" prop="governmentActualCapitalDescription">
                    <tinymce-editor
                        v-model="form.governmentActualCapitalDescription"
                        cosPath="need-manage/img"
                        :disabled="isDetail"
                        :height="400"
                    ></tinymce-editor>
                </a-form-model-item>
            </template>
            <a-form-model-item class="btn-box">
                <a-button class="green-btn" @click="preStep">上一步</a-button>
                <template v-if="!isDetail">
                    <a-button type="primary" class="btn" @click="submit">保存</a-button>
                    <a-button type="primary" @click="submit('release')">保存并发布</a-button>
                </template>
            </a-form-model-item>
        </a-form-model>
    </div>
</template>

<script>
import TinymceEditor from '~/components/tinymce-editor'

export default {
    // 业主信息
    name: 'OwnerInfo',
    components: {
        TinymceEditor
    },
    model: {
        prop: 'allForm',
        event: 'change'
    },
    props: {
        allForm: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },
    data () {
        const checkTitleA = (rule, value, callback) => {
            if (
                this.form.actualCapitalType === 2 &&
                this.form.actualCapitalDescription &&
                !this.form.actualCapitalTitle
            ) {
                callback(new Error('请输入文件标题'))
            } else {
                callback()
            }
        }
        const checkTitleG = (rule, value, callback) => {
            if (
                this.form.governmentActualCapitalType === 2 &&
                this.form.governmentActualCapitalDescription &&
                !this.form.governmentActualCapitalTitle
            ) {
                callback(new Error('请输入文件标题'))
            } else {
                callback()
            }
        }
        const checkTel = (rule, value, callback) => {
            if (!/^[0-9]*$/.test(value) || value.length > 11) {
                callback(new Error('请输入正确的联系方式'))
            } else {
                callback()
            }
        }
        return {
            form: {
                // 单位
                unit: '',
                // 联系人
                contacts: '',
                // 联系方式
                contactsPhoneNumber: '',
                // 招商策划书类型
                actualCapitalType: 1,
                // 招商策划书文件
                actualCapitalPlan: [],
                // 招商策划书标题
                actualCapitalTitle: '',
                // 招商策划书富文本
                actualCapitalDescription: '',
                // 地方政府文件类型
                governmentActualCapitalType: 1,
                // 地方政府文件
                governmentActualCapital: [],
                // 地方政府文件标题
                governmentActualCapitalTitle: '',
                // 地方政府文件富文本
                governmentActualCapitalDescription: ''
            },
            rules: {
                unit: [
                    { required: true, message: '请输入单位', trigger: 'blur' },
                    { max: 100, message: '最多可输入100个字符', trigger: 'change' }
                ],
                contacts: [
                    { required: true, message: '请输入联系人', trigger: 'blur' },
                    { max: 20, message: '最多可输入20个字符', trigger: 'change' }
                ],
                contactsPhoneNumber: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' },
                    { validator: checkTel, trigger: 'blur' }
                ],
                actualCapitalTitle: [{ validator: checkTitleA, trigger: ['change', 'blur'] }],
                governmentActualCapitalTitle: [{ validator: checkTitleG, trigger: ['change', 'blur'] }]
            }
        }
    },
    computed: {
        formType () {
            return this.$route.query.formType || ''
        },
        isDetail () {
            return !!this.$route.query.d
        },
        getNameActualCapitalPlan () {
            let count = -1
            const tempList = []
            this.form.actualCapitalPlan.forEach((item) => {
                let name = ''
                if (item.includes('?name=')) {
                    name = item.split('?name=')[1]
                } else {
                    name = item
                }
                tempList.push({
                    uid: count,
                    name,
                    status: 'done',
                    url: item
                })
                count--
            })
            return tempList
        },
        getNameGovernmentActualCapital () {
            let count = -1
            const tempList = []
            this.form.governmentActualCapital.forEach((item) => {
                let name = ''
                if (item.includes('?name=')) {
                    name = item.split('?name=')[1]
                } else {
                    name = item
                }
                tempList.push({
                    uid: count,
                    name,
                    status: 'done',
                    url: item
                })
                count--
            })
            return tempList
        }
    },
    watch: {
        allForm: {
            deep: true,
            handler (val) {
                this.form = {
                    ...this.form,
                    ...val
                }
            }
        }
    },
    created () {},
    mounted () {},
    methods: {
        preStep () {
            this.$emit('change', {
                ...this.allForm,
                ...this.form,
                currentStep: 0
            })
        },
        submit (type) {
            this.$emit('change', {
                ...this.allForm,
                ...this.form
            })
            setTimeout(() => {
                if (type === 'release') {
                    this.saveForm()
                } else {
                    this.formSubmit()
                }
            })
        },
        async formSubmit () {
            const governmentActualCapitalTitle = this.allForm.governmentActualCapital
                .map(item => item.split('?name=')[1])
                .join(',')
            const actualCapitalTitle = this.allForm.actualCapitalPlan.map(item => item.split('?name=')[1]).join(',')
            const flatten = (arr) => {
                return [].concat(...arr.map(x => (Array.isArray(x) ? flatten(x) : x)))
            }
            const _type = this.allForm.type.filter((item, index) => index < 10)
            const _targetIndustry = this.allForm.targetIndustry
                ? this.allForm.targetIndustry.filter((item, index) => index < 10)
                : []
            const res = await this.$ApiServer['need/update/attractCapitalMerchants']({
                ...this.allForm,
                gis: [this.allForm.cityInfo.longitude, this.allForm.cityInfo.latitude].join(','),
                type: Array.from(new Set(flatten(_type))).join(','),
                multipleTypeList: this.allForm.type
                    .filter((item, index) => index < 10)
                    .map(item => item.join('/'))
                    .join(','),
                multipleTypeName: this.allForm.typeCascader
                    .filter((item, index) => index < 10)
                    .map(item => item.join('/'))
                    .join(','),
                targetCity:
                    this.allForm.targetCity && this.allForm.targetCity.length
                        ? this.allForm.targetCity
                            .filter((item, index) => index < 10)
                            .map(item => Array.isArray(item) ? item[item.length - 1] : item)
                            .join(',')
                        : '',
                targetIndustry:
                    this.allForm.targetIndustry && this.allForm.targetIndustry.length
                        ? Array.from(new Set(flatten(_targetIndustry))).join(',')
                        : '',
                multipleIndustryName:
                    this.allForm.industryCascader && this.allForm.industryCascader.length
                        ? this.allForm.industryCascader
                            .filter((item, index) => index < 10)
                            .map(item => item.join('/'))
                            .join(',')
                        : '',
                multipleIndustryList:
                    this.allForm.targetIndustry && this.allForm.targetIndustry.length
                        ? this.allForm.targetIndustry
                            .filter((item, index) => index < 10)
                            .map(item => item.join('/'))
                            .join(',')
                        : '',
                governmentActualCapital: this.allForm.governmentActualCapital.join(','),
                governmentActualCapitalTitle:
                    this.allForm.governmentActualCapitalType === 1
                        ? governmentActualCapitalTitle
                        : this.allForm.governmentActualCapitalTitle,
                governmentActualCapitalDescription:
                    this.allForm.governmentActualCapitalType === 1
                        ? ''
                        : this.allForm.governmentActualCapitalDescription,
                actualCapitalPlan: this.allForm.actualCapitalPlan.join(','),
                actualCapitalTitle:
                    this.allForm.actualCapitalType === 1 ? actualCapitalTitle : this.allForm.actualCapitalTitle,
                actualCapitalDescription:
                    this.allForm.actualCapitalType === 1 ? '' : this.allForm.actualCapitalDescription,
                id: this.$route.query.id || '',
                currentStep: undefined,
                cityInfo: undefined,
                typeCascader: undefined,
                industryCascader: undefined,
                saveType: 1,
                dataType: this.formType === 'attractCapital' ? 1 : 2,
                videoUrl: this.allForm.videoList.videoUrl,
                imgCoverUrl: this.allForm.videoList.imgCoverUrl,
                videoList: undefined
            })
            if (res.code === 200) {
                this.$message.success(res.message)
                this.$router.push({
                    path: '/need-manage/investment-promotion-list'
                })
            } else {
                this.$message.error(res.message)
            }
        },
        saveForm () {
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    const governmentActualCapitalTitle = this.allForm.governmentActualCapital
                        .map(item => item.split('?name=')[1])
                        .join(',')
                    const actualCapitalTitle = this.allForm.actualCapitalPlan
                        .map(item => item.split('?name=')[1])
                        .join(',')
                    const flatten = (arr) => {
                        return [].concat(...arr.map(x => (Array.isArray(x) ? flatten(x) : x)))
                    }
                    const _type = this.allForm.type.filter((item, index) => index < 10)
                    const _targetIndustry = this.allForm.targetIndustry
                        ? this.allForm.targetIndustry.filter((item, index) => index < 10)
                        : []
                    const res = await this.$ApiServer['need/update/attractCapitalMerchants']({
                        ...this.allForm,
                        gis: [this.allForm.cityInfo.longitude, this.allForm.cityInfo.latitude].join(','),
                        type: Array.from(new Set(flatten(_type))).join(','),
                        multipleTypeList: this.allForm.type
                            .filter((item, index) => index < 10)
                            .map(item => item.join('/'))
                            .join(','),
                        multipleTypeName: this.allForm.typeCascader
                            .filter((item, index) => index < 10)
                            .map(item => item.join('/'))
                            .join(','),
                        targetCity:
                            this.allForm.targetCity && this.allForm.targetCity.length
                                ? this.allForm.targetCity
                                    .filter((item, index) => index < 10)
                                    .map(item => item[item.length - 1])
                                    .join(',')
                                : '',
                        targetIndustry:
                            this.allForm.targetIndustry && this.allForm.targetIndustry.length
                                ? Array.from(new Set(flatten(_targetIndustry))).join(',')
                                : '',
                        multipleIndustryName:
                            this.allForm.industryCascader && this.allForm.industryCascader.length
                                ? this.allForm.industryCascader
                                    .filter((item, index) => index < 10)
                                    .map(item => item.join('/'))
                                    .join(',')
                                : '',
                        multipleIndustryList:
                            this.allForm.targetIndustry && this.allForm.targetIndustry.length
                                ? this.allForm.targetIndustry
                                    .filter((item, index) => index < 10)
                                    .map(item => item.join('/'))
                                    .join(',')
                                : '',
                        governmentActualCapital: this.allForm.governmentActualCapital.join(','),
                        governmentActualCapitalTitle:
                            this.allForm.governmentActualCapitalType === 1
                                ? governmentActualCapitalTitle
                                : this.allForm.governmentActualCapitalTitle,
                        governmentActualCapitalDescription:
                            this.allForm.governmentActualCapitalType === 1
                                ? ''
                                : this.allForm.governmentActualCapitalDescription,
                        actualCapitalPlan: this.allForm.actualCapitalPlan.join(','),
                        actualCapitalTitle:
                            this.allForm.actualCapitalType === 1 ? actualCapitalTitle : this.allForm.actualCapitalTitle,
                        actualCapitalDescription:
                            this.allForm.actualCapitalType === 1 ? '' : this.allForm.actualCapitalDescription,
                        id: this.$route.query.id || '',
                        currentStep: undefined,
                        cityInfo: undefined,
                        typeCascader: undefined,
                        industryCascader: undefined,
                        saveType: 2,
                        dataType: this.formType === 'attractCapital' ? 1 : 2,
                        videoUrl: this.allForm.videoList.videoUrl,
                        imgCoverUrl: this.allForm.videoList.imgCoverUrl,
                        videoList: undefined
                    })
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.$router.push({
                            path: '/need-manage/investment-promotion-list'
                        })
                    } else {
                        this.$message.error(res.message)
                    }
                }
            })
        },
        // 预览大图
        showPicturesModal (url, urls) {
            if (urls.length) {
                this.$picturesModal({
                    url,
                    urls
                })
            }
        },
        toOpen (url) {
            url = url.replace(/\?/g, '%3F').replace(/=/g, '%3D')
            window.open(this.$staticUrl + url, '_blank')
        }
    }
}
</script>

<style scoped lang="less">
.form {
    width: 100%;
    padding-left: 20px;
    padding-top: 1px;
    padding-bottom: 40px;
    position: relative;
    h2 {
        font-size: 16px;
        line-height: 22px;
        padding-left: 6px;
        margin: 10px 0;
        span {
            font-size: 12px;
            color: #9da1a4;
            margin-left: 4px;
        }
        position: relative;
        &:before {
            content: '';
            width: 2px;
            height: 12px;
            background-color: @primary-color;
            position: absolute;
            left: 0;
            top: 50%;
            transform: translate(-100%, -50%);
        }
        &:after {
            width: 100%;
            height: 1px;
            background-color: #f3f3f3;
            position: absolute;
            left: 0;
            bottom: 0;
        }
    }
    .btn-box {
        margin: 20px 0;
        .btn {
            margin: 0 10px;
        }
    }
    ::v-deep {
        .ant-form-item {
            width: 600px;
            margin-left: 20px;
        }
        .ant-tabs,
        .ant-upload {
            width: 600px;
            margin-left: 20px;
        }
        .ant-upload.ant-upload-drag {
            border-style: solid;
        }
    }

    .green-btn {
        border-color: @primary-color;
        color: @primary-color;
    }
}
</style>
